package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.VideoUploadCallbackHistory;
import com.letv.whatslive.model.convert.VideoUploadCallbackHistoryConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by haojiayao on 16-3-29.
 */
@Repository
public class VideoUploadCallbackHistoryDAO extends BaseDAO {

    private final static Logger logger = LoggerFactory.getLogger(VideoUploadCallbackHistoryDAO.class);
    protected String collectionName = "videoUploadCallbackHistory";

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    /**
     * 插入视频上传回调历史信息
     *
     * @param callbackHistory
     */
    public long insertCallbackHistory(VideoUploadCallbackHistory callbackHistory) {

        long id = 0L;
        try {

            DBObject obj = VideoUploadCallbackHistoryConvert.castCallbackHistoryToDBObject(callbackHistory);
            id = this.insert(obj);
        } catch (Exception e) {

            logger.error("insertCallbackHistory error", e);
        }

        return id;
    }

    public VideoUploadCallbackHistory getVideoUploadCallbackHistoryById(Long id) {
        DBObject dbObject = new BasicDBObject();
        dbObject.put("_id", id);
        DBObject result = dbCollection.findOne(dbObject);
        if (result == null) {
            return null;
        }
        VideoUploadCallbackHistory videoUploadCallbackHistory = VideoUploadCallbackHistoryConvert.castDBObjectToCallbackHistory(result);
        return videoUploadCallbackHistory;
    }

    public VideoUploadCallbackHistory getVideoUploadCallbackHistoryByOutkey(Long id) {
        DBObject dbObject = new BasicDBObject();
        dbObject.put("outKey", id);
        DBObject result = dbCollection.findOne(dbObject);
        if (result == null) {
            return null;
        }
        VideoUploadCallbackHistory videoUploadCallbackHistory = VideoUploadCallbackHistoryConvert.castDBObjectToCallbackHistory(result);
        return videoUploadCallbackHistory;
    }

    public List<String> getCodeIdByConditon(VideoUploadCallbackHistory videoUploadCallbackHistory) {

        List<String> list = Lists.newArrayList();
        if (videoUploadCallbackHistory == null) {
            return null;
        }
        DBObject queryCondition = new BasicDBObject();
        queryCondition.put("outKey", videoUploadCallbackHistory.getOutKey());
        queryCondition.put("vType", videoUploadCallbackHistory.getVType());
        DBCursor cur = this.dbCollection.find(queryCondition);
        while (cur.hasNext()) {
            DBObject re = cur.next();
            list.add(ObjectUtils.toString(re.get("codeId")));
        }
        return list;
    }

    /**
     * 根据条件查询视频上传历史列表
     *
     * @param params 查询参数
     * @param orders 排序参数
     */
    public List<VideoUploadCallbackHistory> getAllCallbackHistoryByParams(Map<String, Object> params, Map<String, Object> orders) {

        List<VideoUploadCallbackHistory> callbackHistoryList = Lists.newArrayList();

        try {

            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {

                DBObject dbObject = cur.next();
                VideoUploadCallbackHistory callbackHistory = VideoUploadCallbackHistoryConvert.castDBObjectToCallbackHistory(dbObject);
                callbackHistoryList.add(callbackHistory);
            }
        } catch (Exception e) {

            logger.error("getAllCallbackHistoryByParams error", e);
        }
        return callbackHistoryList;
    }

    /**
     * 根据查询参数Map获取查询条件对象
     *
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params) {

        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {

            if (params.get("id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("id")));
            }

            if (params.get("outKey") != null) {
                query.put("outKey", ObjectUtils.toLong(params.get("outKey")));
            }
            if (params.get("vType") != null) {
                query.put("vType", ObjectUtils.toInteger(params.get("vType")));
            }
            if (params.get("codeId") != null) {
                query.put("codeId", ObjectUtils.toInteger(params.get("codeId")));
            }
            if (params.get("curTask") != null) {
                query.put("curTask", ObjectUtils.toString(params.get("curTask")));
            }
            if (params.get("code") != null) {
                query.put("code", ObjectUtils.toString(params.get("code")));
            }
        }

        return query;
    }

    /**
     * 获取排序对象
     *
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {

        BasicDBObject order = new BasicDBObject();

        if (null != orders && orders.size() > 0) {

            for (String key : orders.keySet()) {

                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        } else {
            //默认按照创建时间排序
            order.append("createTime", -1);
        }
        return order;
    }

    public List<VideoUploadCallbackHistory> getVideoUploadCallbackHistoryListByParams(Map<String, Object> orders, Map<String, Object> params, Integer start, Integer limit) {

        List<VideoUploadCallbackHistory> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip)
                    .sort(order).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                VideoUploadCallbackHistory program = VideoUploadCallbackHistoryConvert.castDBObjectToCallbackHistory(dbObject);
                result.add(program);
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }
}
